<template>
  <div>
    <ElementDialog
      :title="dataForm.id === -1 ? '新增人员信息' : '修改人员信息'"
      width="90%"
      show-full-screen
      height="600px"
      :visible.sync="visible">
      <ElCollapse v-model="activeName" accordion>
        <ElCollapseItem name="1">
          <template #title> 人员基本信息 </template>
          <ElForm
            ref="dataForm"
            :model="dataForm"
            :rules="dataRule"
            label-width="120px"
            @keyup.enter.native="dataFormSubmit()">
            <ElRow :gutter="10">
              <ElCol :span="8">
                <ElFormItem label="人员编号" prop="personNumber">
                  <ElInput v-model="dataForm.personNumber" placeholder="人员编号" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="登录名称" prop="loginname">
                  <ElInput
                    v-model="dataForm.loginname"
                    :disabled="loginNameDisable"
                    placeholder="用户名称"
                    @focus="showSelectUser" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="姓名" prop="name">
                  <ElInput v-model="dataForm.name" placeholder="姓名" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="10">
              <ElCol :span="8">
                <ElFormItem label="身份证号码" prop="idNumber">
                  <ElInput v-model="dataForm.idNumber" placeholder="身份证号码" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="籍贯" prop="nativePlace">
                  <ElInput v-model="dataForm.nativePlace" placeholder="籍贯" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="出生日期" prop="birthday">
                  <ElDatePicker v-model="dataForm.birthday" type="date" placeholder="出生日期" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="10">
              <ElCol :span="16">
                <ElFormItem label="户口所在地" prop="hukou">
                  <ElInput v-model="dataForm.hukou" placeholder="户口所在地" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="婚姻状况" prop="maritalStatus">
                  <FySelect
                    v-model="dataForm.maritalStatus"
                    filterable
                    :dic="maritalStatusOption"
                    placeholder="婚姻状况" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="10">
              <ElCol :span="8">
                <ElFormItem label="性别" prop="gender">
                  <ElRadio v-model="dataForm.gender" label="0" border>女</ElRadio>
                  <ElRadio v-model="dataForm.gender" label="1" border>男</ElRadio>
                  <ElRadio v-model="dataForm.gender" label="2" border>其他</ElRadio>
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="民族" prop="nation">
                  <FySelect v-model="dataForm.nation" filterable :dic="nationOption" placeholder="民族" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="出生地" prop="birthplace">
                  <ElInput v-model="dataForm.birthplace" placeholder="出生地" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="10">
              <ElCol :span="8">
                <ElFormItem label="参加工作时间" prop="workdate">
                  <ElDatePicker
                    v-model="dataForm.workdate"
                    value-format="yyyy-MM-dd"
                    type="date"
                    placeholder="参加工作时间" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="健康状况" prop="health">
                  <FySelect v-model="dataForm.health" filterable :dic="healthOption" placeholder="健康状况" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="最高学历" prop="degree">
                  <FySelect v-model="dataForm.degree" filterable :dic="degreeOption" placeholder="最高学历" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="10">
              <ElCol :span="8">
                <ElFormItem label="人员状态" prop="status">
                  <FySelect v-model="dataForm.status" filterable :dic="statusOption" placeholder="人员状态" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="人员类型" prop="type">
                  <FySelect v-model="dataForm.type" filterable :dic="typeOption" placeholder="人员类型" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="电话号码" prop="telephone">
                  <ElInput v-model="dataForm.telephone" placeholder="电话号码" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="10">
              <ElCol :span="8">
                <ElFormItem label="手机号码" prop="mobile">
                  <ElInput v-model="dataForm.mobile" placeholder="手机号码" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="职    务" prop="post">
                  <FySelect v-model="dataForm.post" filterable :dic="postOption" placeholder="职    务" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="入职本单位时间" prop="enterdeptDate">
                  <ElDatePicker
                    v-model="dataForm.enterdeptDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="入职本单位时间" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="10">
              <ElCol :span="8">
                <ElFormItem label="职称" prop="profesTitle">
                  <FySelect
                    v-model="dataForm.profesTitle"
                    filterable
                    :dic="profesTitleOption"
                    placeholder="请选择职称" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="电子邮件" prop="email">
                  <ElInput v-model="dataForm.emall" placeholder="电子邮件" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="传真" prop="faxno">
                  <ElInput v-model="dataForm.faxno" placeholder="传真" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <!--            <ElRow :gutter="10">-->
            <!--              <ElCol :span="8">-->
            <!--                <ElFormItem label="工号" prop="cardId">-->
            <!--                  <ElInput v-model="dataForm.cardId" placeholder="工号"/>-->
            <!--                </ElFormItem>-->
            <!--              </ElCol>-->
            <!--              <ElCol :span="8">-->
            <!--                <ElFormItem label="退休时间" prop="retireDate">-->
            <!--                  <ElDatePicker-->
            <!--                    v-model="dataForm.retireDate"-->
            <!--                    type="date"-->
            <!--                    value-format="yyyy-MM-dd"-->
            <!--                    placeholder="退休时间"/>-->
            <!--                </ElFormItem>-->
            <!--              </ElCol>-->
            <!--            </ElRow>-->
          </ElForm>
        </ElCollapseItem>
        <ElCollapseItem name="2">
          <template #title> 家庭成员关系信息管理 </template>
          <Familyinfo ref="family" :user-name="dataForm.name" />
        </ElCollapseItem>
        <ElCollapseItem name="3">
          <template #title> 政治面貌信息管理 </template>
          <Politicalinfo ref="political" :user-name="dataForm.name" />
        </ElCollapseItem>
        <ElCollapseItem name="4">
          <template #title> 学历学位信息管理 </template>
          <Education ref="edu" :user-name="dataForm.name" />
        </ElCollapseItem>
        <ElCollapseItem name="5">
          <template #title> 个人简历信息管理 </template>
          <Resume ref="resume" :user-name="dataForm.name" />
        </ElCollapseItem>
      </ElCollapse>
      <template #footer>
        <span class="dialog-footer">
          <ElButton @click="visible = false">取消</ElButton>
          <ElButton v-if="canSubmit" type="primary" @click="dataFormSubmit()">确定</ElButton>
        </span>
      </template>
    </ElementDialog>
    <SelectUser ref="selectUser" select-type="notUserInfo" @getUserData="getUserData" />
  </div>
</template>

<script>
  import { getObj, addObj, putObj, detailsNumber, countIdNumber, getByUserId } from '@/api/admin/userinfo'
  import Education from '../../personnel/education/education'
  import Familyinfo from '../../personnel/familyinfo/familyinfo'
  import Politicalinfo from '../../personnel/politicalinfo/politicalinfo'
  import Resume from '../../personnel/resume/resume'
  import { getDictData } from '@/util/dictionary'

  export default {
    components: {
      Education,
      Familyinfo,
      Politicalinfo,
      Resume
    },
    data() {
      // 验证人员编码
      const validateNumber = (rule, value, callback) => {
        detailsNumber(value).then(response => {
          // 修改状态退出
          if (this.dataForm.id !== -1) callback()
          const result = response.data.data
          if (result !== null) {
            callback(new Error('人员编号已经存在'))
          } else {
            callback()
          }
        })
      }
      // 验证身份证
      const validateIdNumber = (rule, value, callback) => {
        const p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
        // 修改状态退出
        if (this.dataForm.id !== -1) callback()
        if (!p.test(value)) {
          callback(new Error('身份证信息输入错误'))
        } else {
          countIdNumber(value).then(response => {
            const result = response.data.data
            if (result > 0) {
              callback(new Error('此身份证号已经被使用'))
            } else {
              this.dataForm.birthday = `${value.substr(6, 4)}-${value.substr(10, 2)}-${value.substr(12, 2)}`
              this.dataForm.gender = `${parseInt(value.substr(16, 1)) % 2}`
              callback()
            }
          })
        }
      }
      return {
        visible: false,
        canSubmit: false,
        dataForm: {
          id: -1,
          userId: '',
          personNumber: '',
          loginname: '',
          name: '',
          birthday: '',
          nativePlace: '',
          gender: '2',
          hukou: '',
          enterdeptDate: '',
          maritalStatus: '未婚',
          idNumber: '',
          nation: '汉族',
          birthplace: '',
          workdate: '',
          health: '健康',
          degree: '本科毕业生',
          status: '在岗',
          type: '正式',
          telephone: '',
          mobile: '',
          post: '职工',
          retireDate: '',
          profesTitle: '科员',
          email: '',
          faxno: '',
          cardId: ''
        },
        maritalStatusOption: [],
        nationOption: [],
        healthOption: [],
        degreeOption: [],
        statusOption: [],
        typeOption: [],
        postOption: [],
        profesTitleOption: [],
        activeName: '1',
        visibleSelectUser: false,
        dataRule: {
          personNumber: [
            { required: true, message: '人员编号不能为空', trigger: 'blur' },
            { validator: validateNumber, trigger: 'blur' }
          ],
          loginname: [{ required: true, message: '登录名称不能为空', trigger: 'blur' }],
          name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
          hukou: [{ required: true, message: '户口所在地不能为空', trigger: 'blur' }],
          idNumber: [
            { required: true, message: '身份证号码不能为空', trigger: 'blur' },
            { validator: validateIdNumber, trigger: 'blur' }
          ],
          mobile: [{ required: true, message: '手机号码不能为空', trigger: 'blur' }]
        },
        loginNameDisable: false
      }
    },
    methods: {
      async init(id, userId, loginname) {
        this.dataForm.id = id || -1
        this.visible = true
        this.canSubmit = true
        // 初始化默认第一个选项卡
        this.activeName = '1'
        // 获取婚姻状况选项信息
        this.getMaritalStatus()
        // 获取名族选项信息
        this.getNation()
        // 获取健康选项信息
        this.getHealth()
        // 获取最高学历选项信息
        this.getDegree()
        // 获取人员状态选项信息
        this.getStatus()
        // 获取人员类型选项信息
        this.getType()
        // 获取职务选项信息
        this.getPost()
        // 获取职称信息
        this.getProfesTitle()
        await this.$nextTick()
        this.$refs.dataForm.resetFields()
        if (this.dataForm.id !== -1) {
          getObj(this.dataForm.id).then(response => {
            this.dataForm = response.data.data
          })
          this.loginNameDisable = true
        } else if (userId !== undefined && loginname !== undefined) {
          this.dataForm.userId = userId
          this.dataForm.loginname = loginname
          this.loginNameDisable = true

          getByUserId(userId).then(response => {
            if (!this.$isBlank(response.data.data)) {
              this.dataForm = response.data.data
            }
          })
        } else {
          this.loginNameDisable = false
          this.showSelectUser()
        }
        this.$refs.edu.userInit(this.dataForm.id)
        this.$refs.family.userInit(this.dataForm.id)
        this.$refs.resume.userInit(this.dataForm.id)
        this.$refs.political.userInit(this.dataForm.id)
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            this.canSubmit = false
            if (this.dataForm.id !== -1) {
              putObj(this.dataForm)
                .then(data => {
                  this.$notify.success('修改成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                })
                .catch(() => {
                  this.canSubmit = true
                })
            } else {
              addObj(this.dataForm)
                .then(data => {
                  const resData = data.data
                  this.$refs.family.groupSave(resData.data)
                  this.$refs.political.groupSave(resData.data)
                  this.$refs.edu.groupSave(resData.data)
                  this.$refs.resume.groupSave(resData.data)
                  this.$notify.success('添加成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                })
                .catch(() => {
                  this.canSubmit = true
                })
            }
          }
        })
      },
      showSelectUser() {
        this.visibleSelectUser = true
        this.$nextTick(() => {
          this.$refs.selectUser.init()
        })
      },
      getUserData(userData) {
        this.dataForm.userId = userData.userId // 用户id
        this.dataForm.loginname = userData.username // 用户名称
        this.dataForm.mobile = userData.realPhone // 真实电话号码
        this.dataForm.name = userData.username // 用户姓名
      },
      getMaritalStatus() {
        getDictData('婚姻状况').then(response => {
          this.maritalStatusOption = response
        })
      },
      getNation() {
        getDictData('民族').then(response => {
          this.nationOption = response
        })
      },
      getHealth() {
        getDictData('健康状况').then(response => {
          this.healthOption = response
        })
      },
      getDegree() {
        getDictData('最高学历').then(response => {
          this.degreeOption = response
        })
      },
      getStatus() {
        getDictData('人员状态').then(response => {
          this.statusOption = response
        })
      },
      getType() {
        getDictData('人员类型').then(response => {
          this.typeOption = response
        })
      },
      getPost() {
        getDictData('职务').then(response => {
          this.postOption = response
        })
      },
      getProfesTitle() {
        getDictData('profes_title').then(data => {
          this.profesTitleOption = data
        })
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }

        return {
          id: node.value,
          label: node.label,
          children: node.children
        }
      }
    }
  }
</script>
